import {
  responseSuccess,
  responseError,
} from '@/share/interface/standard';
import { AppDataSource } from '@/data-source';
import { Auth } from '@/entity/Auth';
import { EXPIRES_IN } from '@/share/config';
import type { NextFunction, Request, Response } from 'express';
const svgCaptcha = require('svg-captcha');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
// const secretKey = crypto.randomBytes(64).toString('hex');

export class AuthController {
  /**
   * 生成验证码
   * Method: GET
   */
  async svg_captcha(req: Request, res: Response) {
    const captcha = svgCaptcha.create({
      size: 4, // 字符个数
      fontSize: 50, // 字体大小
      width: 120, // 图片宽度
      height: 40, // 图片高度
      noise: 0, // 干扰线数量
      color: false, // 是否开启颜色，默认为黑色
      background: '#cc9966',
      ignoreChars: '0oO1iIlL', // 验证码字符中排除 0o1i
    });
    req.session.svg_captcha = captcha.text;
    res.type('svg');
    console.log(req.session.svg_captcha);
    res.send(Buffer.from(captcha.data)); // 使用res.send()发送SVG内容
  }

  /**
   * 后台登录验证接口
   * method: POST JSON
   */
  async adminLogin(req: Request, res: Response, next: NextFunction) {
    const { username, password, captcha } = req.body;
    const session_svg_captcha = req.session.svg_captcha;
    req.session.svg_captcha = '';
    console.log(session_svg_captcha, captcha);

    const auth = await AppDataSource.manager.findOne(Auth, {
      where: { username, password },
    });
    if (!auth) {
      return responseError('用户名或密码错误');
    }

    if (
      !session_svg_captcha ||
      session_svg_captcha?.toLowerCase() !== captcha?.toLowerCase()
    ) {
      return responseError('验证码错误');
    }

    const token = jwt.sign(
      // sub: auth.id,
      { model: 'admin' },
      'type-orm-chf',
      {
        expiresIn: EXPIRES_IN,
      }
    );

    return responseSuccess({ token });
    // 验证密码
    // const isMatch = await crypto.compare(password, user.password);
    // if (!isMatch) {
    //   return 'password error';
    // }
  }

  /**
   * 后台修改密码接口
   */
  async adminChangePassword(req: Request) {
    const { username, password, new_password } = req.body;
    const auth = await AppDataSource.manager.findOne(Auth, {
      where: { username, password },
    });
    if (!auth) {
      return responseError('用户名或密码错误');
    }
    await AppDataSource.manager.update(
      Auth,
      { username },
      { password: new_password }
    );
    return responseSuccess('修改成功');
  }

  /**
   * 后台退出当前会话登录
   * Method: GET
   */
  async adminLogOut(req: Request) {
    req.session.login = undefined;
    // 清除 token
    return responseSuccess('退出成功');
  }
}
